package com.graduation_design.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.graduation_design.entity.SysUser;
import com.graduation_design.entity.SysUserRole;
import com.graduation_design.service.SysRoleService;
import com.graduation_design.service.SysUserRoleService;
import com.graduation_design.service.SysUserService;
import com.graduation_design.mapper.SysUserMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
* @author 从南
* @description 针对表【sys_user】的数据库操作Service实现
* @createDate 2024-02-16 18:15:59
*/
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser>
    implements SysUserService{

    @Resource
    SysRoleService sysRoleService;

    @Resource
    SysUserRoleService sysUserRoleService;

    /**
     * 获取管理员列表
     * 在列表中需要显示每个管理员对应的角色信息，所以需要把管理员对应的角色一起查出来
     */
    @Override
    public Page<SysUser> getPage(Page page, SysUser sysUser) {

        Page<SysUser> pageData = this.page(page, new QueryWrapper<SysUser>()
                .like(StrUtil.isNotBlank(sysUser.getUsername()), "username", sysUser.getUsername())
                .orderByDesc("created")
        );

        pageData.getRecords().forEach(u -> {
            u.setRoles(sysRoleService.listRolesByUserId(u.getId()));
        });

        return pageData;
    }

    /**
     * 删除管理员
     * 需要把关联的中间表也删除
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBath(Long... ids) {
        this.removeBatchByIds(Arrays.asList(ids));
        // 同步删除中间表
        sysUserRoleService.remove(new QueryWrapper<SysUserRole>()
                .in("user_id", Arrays.asList(ids))
        );
    }

    /**
     * 分配角色
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setRole(Long userId, Long... roleIds) {

        List<SysUserRole> userRoles = new ArrayList<>();

        Arrays.stream(roleIds).forEach(roleId -> {
            SysUserRole userRole = new SysUserRole();
            userRole.setRoleId(roleId);
            userRole.setUserId(userId);

            userRoles.add(userRole);
        });

        // 先删除原来的
        sysUserRoleService.remove(new QueryWrapper<SysUserRole>()
                .eq("user_id", userId)
        );

        sysUserRoleService.saveBatch(userRoles);
    }
}




